﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.Unity;
using Microsoft.Practices.ServiceLocation;
using RMS.Utils.BootStrapper;
using RMS.Utils.ModuleInitilize.Configuration;

namespace RMS.Utils.ModuleInitilize
{
    public class ModuleInitilizerTask : IBootStrapperTask
    {
        private readonly IUnityContainer container;
        private readonly List<ModuleInitilizerBase> modules;
        public ModuleInitilizerTask()
        {
            this.container = new UnityContainer();
            this.modules = new List<ModuleInitilizerBase>();
        }
        public void Execute()
        {
            ServiceLocator.SetLocatorProvider(() => new UnityServiceLocator(container));
            foreach (Module ModuleElement in ModuleInitilizerSection.Instance.Modules)
            {
                var module = Activator.CreateInstance(ModuleElement.Assembly) as ModuleInitilizerBase;
                if (module != null)
                {
                    RegisterModule(module);
                    module.OnInitilizeContainer(this.container);
                }
            }
        }
        private void RegisterModule(ModuleInitilizerBase module)
        {
            this.modules.Add(module);
        }
    }
}
